from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
import time


def register_middleware(app: FastAPI):

    app.add_middleware(
        CORSMiddleware,
        allow_origin_regex='https?://.*',
        allow_credentials=True,
        allow_methods=['*'],
        allow_headers=['*'],
    )

    # 中间件
    @app.middleware("http")
    async def test(request: Request, call_next):
        start_time = time.time()
        response = await call_next(request)
        process_time = time.time() - start_time
        response.headers["X-Process-Time"] = str(process_time)
        return response
